package com.itheima.chapter06.service;

import com.itheima.chapter06.domain.Comment;
import com.itheima.chapter06.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class ApiCommentService {
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    private String getCommentKey(int id) {
        return Comment.class.getCanonicalName() + "_" + id;
    }
    public Comment findById(Integer id) {
        Object object = redisTemplate.opsForValue().get(getCommentKey(id));
        if (object != null) {
            return (Comment) object;
        }

        Optional<Comment> optional = commentRepository.findById(id);
        if (optional.isPresent()) {
            Comment comment = optional.get();
            redisTemplate.opsForValue().set(getCommentKey(id), comment, 1, TimeUnit.DAYS);
            return comment;
        }
        return null;
    }
    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        redisTemplate.opsForValue().set(getCommentKey(comment.getId()), comment);
        return comment;
    }
    public void deleteComment(Integer id) {
        commentRepository.deleteById(id);
        redisTemplate.delete(getCommentKey(id));
    }
}
